webapp = "admin";
$(function() {

	/**
	 * 站内信息
	 */
	$("#addPrepare").bind("click", function() {
		$('#addPrepare').load('2.html', callback);
	});

	$("#setUp").bind("click",function() {
		$('#setUpDialog').dialog({
			title : '设置',
			width : 400,
			height : 220,
			inline : false,
			closed : false,
			cache : false,
		    onClose:function(){
		    	destroy('setUpDialog','#dialogDiv');
		    },
			
			modal : true,
			content : "<div class='alert-div'><ul><li><a href='#' onclick='changePassWords();'>密码修改</a></li></ul></div>"
		});
	});
	
	findUserMenuByUserId();
	
	if($("#pwdIsValid").val() == "false"){
		changePassWords();
	}
});


/**
 * 通过用户ID获取用户菜单
 */
function findUserMenuByUserId(callback) {
	$.ajax({
		type : "GET",
		url : ctx + "/role/findUserMenuByUserId",
		dataType : "json",
		success : function(data) {
			if(!showMsg(data)){
				return;
			}
			addSencondMenu(data.content);
		}
	});
}

var curMenu = null, zTree_Menu = null;
var settingMenu = {
	view: {
		showLine: true,
		selectedMulti: false,
		dblClickExpand: false
	},
	data: {
		simpleData: {
			enable: true,
			pIdKey: "pid",
		},
		key:{
			name:'name'
		}
	},
	callback: {
		onNodeCreated: this.onNodeCreated,
		beforeClick: this.beforeClick,
		onClick: this.onClick
	}
};

function beforeClick(treeId, node) {
	if (node.isParent) {
		if (node.level === 0) {
			var pNode = curMenu;
			while (pNode && pNode.level !==0) {
				pNode = pNode.getParentNode();
			}
			if (pNode !== node) {
				var a = $("#" + pNode.tId + "_a");
				a.removeClass("cur");
				zTree_Menu.expandNode(pNode, false);
			}
			a = $("#" + node.tId + "_a");
			a.addClass("cur");

			var isOpen = false;
			for (var i=0,l=node.children.length; i<l; i++) {
				if(node.children[i].open) {
					isOpen = true;
					break;
				}
			}
			if (isOpen) {
				zTree_Menu.expandNode(node, true);
				curMenu = node;
			} else {
				zTree_Menu.expandNode(node.children[0].isParent?node.children[0]:node, true);
				curMenu = node.children[0];
			}
		} else {
			zTree_Menu.expandNode(node);
		}
	}
	return !node.isParent;
}
function onClick(e, treeId, node) {
	if(node.path.length == 0)
		return;
	$('#content').panel('open').panel('refresh', ctx + node.path);
	curMenu = node;
}

/**
 * 添加横向菜单（二级）
 * 
 * @param data
 */
function addSencondMenu(data) {
	var lis = $("#css3menu li");

	for (var i = 0; i < data.length; i++) {
		if(data[i].level == 2){
			$("#css3menu").append(
					"<li id='" + i + "'><a id='" + data[i].id + "' href='#' name='"
							+ data[i].name + "'>" + data[i].name + "</a></li>");
		}
	}

	$("#css3menu li").bind('click', function() {
		$(this).siblings().removeClass();
		$(this).addClass('select');
	});

	$('#css3menu a').click(function() {
		$('#css3menu a').removeClass('active');
		$(this).addClass('active');

		var menuData = new Array();
		for (var i = 0; i < data.length; i++) {
			if($(this).attr("id") == data[i].pid && data[i].level == 3){
				menuData.push(data[i]); 
			}
		}
		
		for (var i = 0; i < menuData.length; i++) {
			for (var j = 0; j < data.length; j++) {
				if(data[j].pid == menuData[i].id && data[j].level ==4){
					menuData.push(data[j]); 
				}
			}
		}
		addNav(menuData);
	});
	$("#css3menu a:eq(0)").trigger('click');
}


/**
 * 添加左侧导航菜单项
 * 
 * @param data
 */
function addNav(data) {
	if(zTree_Menu != null){
		zTree_Menu.destroy("treeDemo");
	}
	$.fn.zTree.init($("#treeDemo"), settingMenu, data);
	zTree_Menu = $.fn.zTree.getZTreeObj("treeDemo");
	curMenu = zTree_Menu.getNodes()[0].children[0];
	zTree_Menu.selectNode(curMenu);
	var a = $("#" + zTree_Menu.getNodes()[0].tId + "_a");
	a.addClass("cur");
	a.addClass("first");
	var a = $("#" + zTree_Menu.getNodes()[zTree_Menu.getNodes().length-1].tId + "_a");
	a.addClass("last");
	if(zTree_Menu.setting.callback.onClick != null){
		zTree_Menu.setting.callback.onClick(null, zTree_Menu.setting.treeId, curMenu);//调用事件
	}
}

/**
 * 清除当前面板信息
 */
function clearnav() {

	clearnavAll();

	var pp = $('#wnav').accordion('getSelected');

	if (pp) {
		var title = pp.panel('options').title;
		$('#wnav').accordion('remove', title);
	}
}

/**
 * 清空 accordion 所有面板项
 */
function clearnavAll() {
	var pp = $("#wnav").accordion("panels");

	$.each(pp, function(i, n) {
		if (n) {
			var t = n.panel('options').title;

			$('#wnav').accordion('remove', t);
		}
	});

	pp = $("#wnav").accordion("panels");

	if (pp.length > 0) {
		clearnavAll();
	} else {
		return;
	}
}

function addUrl(url) {
	//$('#content').empty();
	$('#content').panel('open').panel('refresh', ctx + url);
}

/**
 * 初始化左侧
 */
function InitLeftMenu() {

	hoverMenuItem();

	$('#wnav li a').on('click', function() {
		$('#wnav li div').removeClass("selected");

		$(this).parent().addClass("selected");

	});

}

/**
 * 菜单项鼠标Hover
 */
function hoverMenuItem() {
	$("#wnav").find('a').hover(function() {
		$(this).parent().addClass("hover");
	}, function() {
		$(this).parent().removeClass("hover");
	});
}

/**
 * 登录密码修改
 */
function changePassWords(){
	$('#dialog').dialog({
	    title: '密码修改',
	    width: 500,
	    height: 250,
	    inline:false,
	    closed: false,
	    closable:false,
	    cache: false,
	    modal: true,
	    href: ctx + '/web/system/user/password.jsp',
	    onClose:function(){
	    	destroy('dialog','#dialogDiv');
	    },
	    buttons: [{
            text:'确定',
            iconCls:'icon-ok',
            handler:function(){                    
                	var bool = $("#passwordform").form('enableValidation').form('validate');
                	if(!bool){
                		return;
                	}
                	changePassWord();             
            }
        },{
            text:'取消',
            iconCls:'icon-cancel',
            handler:function(){
            	$('#dialog').dialog('close');
            }
        }]
	});
}

/**
 * 修改密码
 * @param username
 * @param oldPassword
 * @param newPassword
 */
function changePassWord(username, oldPassword, newPassword) {
	var username = $("#index #username").val();
	var oldPassword = $("#oldPassword").textbox('getValue');
	var newPassword = $("#newPassword").textbox('getValue');
	$.ajax({
		type : "POST",
		url : ctx + "/user/changePassword",
		data : {
			username : username,
			oldPassword : oldPassword,
			newPassword : newPassword
		},
		dataType : "json",
		success : function(data) {
			if(!showMsg(data,"密码修改成功")){
				return;
			}
			$('#dialog').dialog('close');
			top.location.href = ctx + "/logOut";
		}
	});
}


/**
 * 登录密码修改
 */
/*function changePassWords() {
	$('#dialog').dialog({
		title : '密码修改',
		width : 500,
		height : 560,
		inline : false,
		closed : false,
		cache : false,
		modal : true,
	    onClose:function(){
	    	destroy('dialog','#dialogDiv');
	    },
	    onLoad:function(){
	    	$("#newPassword").textbox({validType:['pwd','length[8,20]']});
	    	
	    },
	    content : "<form id='addform' class='easyui-form'>" +
						"<div style='margin:30px'>" +
				           "<div style='padding-bottom:8px'><span style='width:75px;float:left;'>&nbsp;原密码：</span><input id='oldPassword' class='easyui-textbox' type='password' style='width:60%;height:30px;padding:12px;float:left;' data-options='required:true,validType:\"length[8,20]\",missingMessage:\"原密码必须填写\",invalidMessage:\"密码为8-16个字符！\"'></div>" +
				           "<div style='padding-bottom:8px'><span style='width:75px;float:left;'>&nbsp;新密码：</span><input class='easyui-textbox' id='newPassword' type='password' style='width:60%;height:30px;padding:12px;float:left;' data-options='required:true,validType:\"[pwd]\",missingMessage:\"新密码必须填写\",invalidMessage:\"密码为8-16个字符！\"'></div>" +
				           "<div style='padding-bottom:8px'><span style='width:75px;float:left;'>&nbsp;新密码：</span><div id=\"PasswordCheck\"  style=\"width:60%;height:30px;padding:12px;\"></div></div>" +
				           "<div style='padding-bottom:8px'><span style='width:75px;float:left;'>确认密码：</span><input class='easyui-textbox' id='pwd' type='password' style='width:60%;height:30px;padding:12px;float:left;' data-options='required:true,validType:\"equalTo[newPassword]\",missingMessage:\"确认密码必须填写\",invalidMessage:\"两次输入的密码不一致\"'></div>" +
				           "<div style='padding-bottom:8px'><span style='width:300px;float:left;color:red'>&nbsp;&nbsp;注意：密码修改成功后，自动跳转至登录页；</span></div>" +
				           //"<div style='padding-bottom:8px'><span style='width:75px;float:left;'>&nbsp;密码强度：</span><div id=\"PasswordCheck\"  style=\"text-align:center;width:60%;\"></div></div>" +
				           "</div>" +
		          "</form>",
		buttons : [
				{
					text : '确定',
					iconCls : 'icon-ok',
					handler : function() {
						var bool = $("#addform").form(
								'enableValidation').form(
								'validate');
						if (!bool) {
							return;
						}
						changePassWord();
					}
				}, {
					text : '取消',
					iconCls : 'icon-cancel',
					handler : function() {
						$('#dialog').dialog('close');
					}
				} ]
	});
}*/